<?php

namespace App\Console\Commands\SiteLocation;

use App\Enums\OpenShop\AreaBaseEnum;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\Wanggui\CustomerDepartmentDevelopmentManagerModel;
use App\Models\Wanggui\CustomerDepartmentSiteLocationRelationModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use App\Service\Common\AreaService;
use Illuminate\Console\Command;

class SyncDevelopmentManagerTaskInfo extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'siteLocation:sync-development-manager-task-info {--rmsUserIds=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步开发经理任务信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {

        $rmsUserIds = $this->option('rmsUserIds');

        $rmsUserIdArr = [];

        if (mb_strlen($rmsUserIds)) {
            $rmsUserIdArr = explode(',', $rmsUserIds);
        }

        $insertData = [];
        KmsUser::query()
            ->when(count($rmsUserIdArr), function ($query) use ($rmsUserIdArr) {
                $query->whereIn('rmsUserId', $rmsUserIdArr);
            })
            ->when(!count($rmsUserIdArr), function ($query) use ($rmsUserIdArr) {
                $query->where('rootDepartmentName', '选址开发中心');
            })
            ->where('rmsUserId', '>', 0)
            ->with(['siteTaskRel', 'followUpLastRel'])
            ->get()
            ->map(function (KmsUser $kmsUser) use (&$insertData) {
                $taskCount   = $kmsUser->siteTaskRel->count();
                $sTaskCount  = $kmsUser->siteTaskRel->where('grade', CustomerDepartmentTaskModel::GRADE_S)->count();
                $aTaskCount  = $kmsUser->siteTaskRel->where('grade', CustomerDepartmentTaskModel::GRADE_A)->count();
                $bTaskCount  = $kmsUser->siteTaskRel->where('grade', CustomerDepartmentTaskModel::GRADE_B)->count();
                $cTaskCount  = $kmsUser->siteTaskRel->where('grade', CustomerDepartmentTaskModel::GRADE_C)->count();
                $cityArr     = [];                      // 获得涉及的城市
                $districtArr = [];                      // 获得涉及的地域
                $taskIdsArr  = [];
                foreach ($kmsUser->siteTaskRel as $siteTaskRel) {
                    $prefixAddressArr = explode('-', $siteTaskRel->prefixAddress);
                    if (isset($prefixAddressArr[1])) {
                        $cityArr[$prefixAddressArr[1]] = $prefixAddressArr[1];
                    }

                    $taskIdsArr[] = $siteTaskRel->id;

                    if ($siteTaskRel->districtCode > 0) {
                        $region = AreaBaseEnum::provinceCodeToRegion($siteTaskRel->provinceCode);
                        if ($region != '') {
                            $districtArr[$region] = $region;
                        }
                    }
                }

                // 岗位状态
                $isResigned = KmsUser::IS_RESIGNED_OFF; //在职
                if ($kmsUser->isResigned == KmsUser::IS_RESIGNED_ON || $kmsUser->isExited == KmsUser::IS_RESIGNED_ON) {
                    $isResigned = KmsUser::IS_RESIGNED_ON; //离职
                }

                // 最新跟进时间
                $lastFollowUpTime = '-';
                if (count($kmsUser->followUpLastRel)) {
                    $lastFollowUpTime = $kmsUser->followUpLastRel->first()->createdAt->timestamp;
                }

                // 获取任务关联的房源和选址
                $relationModel = CustomerDepartmentSiteLocationRelationModel::query()
                    ->whereIn('taskId', $taskIdsArr);


                $insertData[] = [
                    'rmsUserId'           => $kmsUser->rmsUserId,
                    'name'                => $kmsUser->nickname . '(' . $kmsUser->name . ')',
                    'phone'               => $kmsUser->mobile,
                    'taskCount'           => $taskCount,
                    'sTaskCount'          => $sTaskCount,
                    'aTaskCount'          => $aTaskCount,
                    'saTaskCount'         => $sTaskCount + $aTaskCount,
                    'bTaskCount'          => $bTaskCount,
                    'cTaskCount'          => $cTaskCount,
                    'sTaskRatio'          => $taskCount ? (int)($sTaskCount / $taskCount * 100) : 0,
                    'aTaskRatio'          => $taskCount ? (int)($aTaskCount / $taskCount * 100) : 0,
                    'saTaskRatio'         => $taskCount ? (int)(($sTaskCount + $aTaskCount) / $taskCount * 100) : 0,
                    'bTaskRatio'          => $taskCount ? (int)($bTaskCount / $taskCount * 100) : 0,
                    'cTaskRatio'          => $taskCount ? (int)($cTaskCount / $taskCount * 100) : 0,
                    'effectiveClueCount'  => $kmsUser->siteTaskRel->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE)->count(),
                    'effectiveHouseCount' => (clone $relationModel)->where('source', OpenShopSiteLocationModel::SOURCE_HOUSING)->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE)->count(),
                    'siteLocationCount'   => (clone $relationModel)->where('source', OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION, CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM])->count(),
                    'taskDistrict'        => implode(',', array_values($districtArr)),
                    'taskCity'            => implode(',', array_values($cityArr)),
                    'onTheJobTime'        => $kmsUser->joinTime,
                    'followUpTime'        => $lastFollowUpTime,
                    'isResigned'          => $isResigned,
                ];
            });

        foreach ($insertData as $insertDatum) {
            $developmentManagerModel                      = CustomerDepartmentDevelopmentManagerModel::query()
                ->updateOrCreate([
                    'phone' => $insertDatum['phone']
                ]);
            $developmentManagerModel->rmsUserId           = $insertDatum['rmsUserId'];
            $developmentManagerModel->name                = $insertDatum['name'];
            $developmentManagerModel->taskCount           = $insertDatum['taskCount'];
            $developmentManagerModel->sTaskCount          = $insertDatum['sTaskCount'];
            $developmentManagerModel->aTaskCount          = $insertDatum['aTaskCount'];
            $developmentManagerModel->saTaskCount         = $insertDatum['saTaskCount'];
            $developmentManagerModel->bTaskCount          = $insertDatum['bTaskCount'];
            $developmentManagerModel->cTaskCount          = $insertDatum['cTaskCount'];
            $developmentManagerModel->sTaskRatio          = $insertDatum['sTaskRatio'];
            $developmentManagerModel->aTaskRatio          = $insertDatum['aTaskRatio'];
            $developmentManagerModel->saTaskRatio         = $insertDatum['saTaskRatio'];
            $developmentManagerModel->bTaskRatio          = $insertDatum['bTaskRatio'];
            $developmentManagerModel->cTaskRatio          = $insertDatum['cTaskRatio'];
            $developmentManagerModel->effectiveClueCount  = $insertDatum['effectiveClueCount'];
            $developmentManagerModel->effectiveHouseCount = $insertDatum['effectiveHouseCount'];
            $developmentManagerModel->siteLocationCount   = $insertDatum['siteLocationCount'];
            $developmentManagerModel->taskDistrict        = $insertDatum['taskDistrict'];
            $developmentManagerModel->taskCity            = $insertDatum['taskCity'];
            $developmentManagerModel->onTheJobTime        = $insertDatum['onTheJobTime'];
            $developmentManagerModel->followUpTime        = $insertDatum['followUpTime'];
            $developmentManagerModel->isResigned          = $insertDatum['isResigned'];
            $developmentManagerModel->save();
        }
    }
}
